package com.itown.expo.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import webframe.common.file.FileTransferHelper;
import webframe.common.file.MyUploadFileRenamePolicy;
import webframe.common.helper.FormatTransformHelper;

import com.itown.expo.controller.base.MyBaseCommandController;
import com.itown.expo.model.DeclGoodsImg;
import com.itown.expo.model.Goods;

public class GoodsImgUploadController extends MyBaseCommandController {

	@Override
	protected ModelAndView handleInner(HttpServletRequest request,
			HttpServletResponse response, Object command) {
		Long goodsId = Long.parseLong(FileTransferHelper.getParameter(request,
				"goodsId"));
		Goods goods = getServiceContainer().getFileBizService().findGoodsById(
				goodsId);
		// 保存上传文件
		Map<File, MultipartFile> files = FileTransferHelper.storageUploadFile(
				request, "upload");
		Set<File> factFiles = files.keySet();
		List<DeclGoodsImg> fileRecords = new ArrayList<DeclGoodsImg>();
		if (factFiles.size() != 0) {
			for (File file : factFiles) {
				// 创建缩略图
				File previewImg = new File(FormatTransformHelper
						.getRealFilePathByKey("preview"),
						MyUploadFileRenamePolicy.getFileNameNotExtName(file)
								+ ".jpg");
				FileTransferHelper.createPreviewImage(file, previewImg);

				// 数据库对象
				DeclGoodsImg goodsImg = new DeclGoodsImg();
				goodsImg.setDeclNo(goods.getDeclNo());
				goodsImg.setGoodsNo(goods.getGoodsNo());
				goodsImg.setGoodsId(goodsId);
				goodsImg.setType(1L);
				goodsImg.setFileName(file.getName());
				goodsImg.setPreviewImgName(previewImg.getName());
				goodsImg.setContentType(files.get(file).getContentType());
				goodsImg.setRemark(FileTransferHelper.getParameter(request,
						files.get(file).getName() + "Remark"));
				fileRecords.add(goodsImg);
			}
		}

		// 删除文件
		String deletefiles = FileTransferHelper.getParameter(request,
				"deleteFiles");
		if (deletefiles != null && deletefiles.trim().length() != 0) {
			List<Long> deleteFileId = new ArrayList<Long>();
			String[] ids = deletefiles.split(";");
			for (int i = 0; i < ids.length; i++) {
				deleteFileId.add(Long.parseLong(ids[i]));
			}
			getServiceContainer().getFileBizService().deleteGoodsImgFiles(
					deleteFileId, "upload", "preview");
		}

		if (fileRecords.size() != 0) {
			getServiceContainer().getFileBizService().saveGoodsImgFiles(
					fileRecords);
		}
		return new ModelAndView(new RedirectView("GoodsImgUpload.html?id="
				+ goodsId.toString()));
	}

}
